from tkinter import *
from PIL import Image, ImageOps, ImageGrab
import numpy as np
from tkinter import filedialog, messagebox
import tensorflow as tf

model = tf.keras.models.load_model('mnist_cnn_model.h5')




registered_users = {}
def predict_digit(image):
    image = ImageOps.invert(image)
    image = image.resize((28, 28)).convert('L')
    image_array = np.array(image) / 255.0
    image_array = image_array.reshape(1, 28, 28, 1)
    prediction = model.predict(image_array)
    digit = np.argmax(prediction)
    return digit


def recognize_single_digit(image):
    digit = predict_digit(image)
    result_label.config(text=f"预测的数字为: {digit}")


def predict_two_digits(image):
    # 切割图像成两部分
    width, height = image.size
    half_width = width // 2
    left_half = image.crop((0, 0, half_width, height))
    right_half = image.crop((half_width, 0, width, height))
    
    # 分别预测两个数字
    left_digit = predict_digit(left_half)
    right_digit = predict_digit(right_half)
    
    # 组合两个数字成两位数
    two_digit_number = left_digit * 10 + right_digit
    return two_digit_number

def recognize_two_digits(image):
    two_digit_number = predict_two_digits(image)
    result_label.config(text=f"预测的两位数为: {two_digit_number}")

def recognize_from_file():
    file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_path:
        image = Image.open(file_path)
        recognize_two_digits(image)

def recognize_from_canvas():
    x0 = canvas.winfo_rootx()
    y0 = canvas.winfo_rooty()
    x1 = x0 + canvas.winfo_width()
    y1 = y0 + canvas.winfo_height()
    img = ImageGrab.grab(bbox=(x0, y0, x1, y1))
    recognize_two_digits(img)



def show_recognition_page():
    global title_label, canvas, button_clear_canvas, button_recognize_single_digit_on_canvas, button_upload_image, result_label
    title_label.config(text="手写数字识别应用", font=("Arial", 20, "bold"), fg="blue")
    title_label.pack(pady=20)

    canvas.pack(pady=10)
    button_clear_canvas.pack(pady=10)
    button_recognize_single_digit_on_canvas.pack(pady=10)
    button_upload_image.pack(pady=10)
    result_label.pack(pady=20)


def login_page():
    global login_frame
    login_frame = Frame(root)
    login_frame.pack()

    username_label = Label(login_frame, text="用户名:", font=("Arial", 12))
    username_label.pack()
    username_entry = Entry(login_frame, font=("Arial", 12))
    username_entry.pack()

    password_label = Label(login_frame, text="密码:", font=("Arial", 12))
    password_label.pack()
    password_entry = Entry(login_frame, show="*", font=("Arial", 12))
    password_entry.pack()

    def login():
        username = username_entry.get()
        password = password_entry.get()

        if username in registered_users and registered_users[username] == password:
            login_frame.pack_forget()  # 隐藏登录页面
            show_recognition_page()  # 显示手写数字识别页面
        else:
            messagebox.showerror("Error", "用户名或密码错误")

    login_button = Button(login_frame, text="登录", command=login, font=("Arial", 12))
    login_button.pack(pady=10)

def register_page():
    global register_frame
    register_frame = Frame(root)
    register_frame.pack()
    new_username_label = Label(register_frame, text="新用户名:", font=("Arial", 12))
    new_username_label.pack()
    new_username_entry = Entry(register_frame, font=("Arial", 12))
    new_username_entry.pack()
    new_password_label = Label(register_frame, text="新密码:", font=("Arial", 12))
    new_password_label.pack()
    new_password_entry = Entry(register_frame, show="*", font=("Arial", 12))
    new_password_entry.pack()
    def register():
        new_username = new_username_entry.get()
        new_password = new_password_entry.get()
        registered_users[new_username] = new_password
        messagebox.showinfo("Success", "注册成功!")
        register_frame.pack_forget()  # 隐藏注册页面
        login_page()  # 显示登录页面
    register_button = Button(register_frame, text="注册", command=register, font=("Arial", 14))
    register_button.pack(pady=10)

root = Tk()
root.title("系统主页面")
root.geometry("1000x800")
root.configure(bg="lightgray")
title_label = Label(root, text="登录页面", font=("Arial", 16))
title_label.pack(pady=60)
login_button = Button(root, text="登录", command=login_page, font=("Arial", 14))
login_button.pack()
register_button = Button(root, text="注册", command=register_page, font=("Arial", 14))
register_button.pack()
canvas = Canvas(root, width=200, height=200, bg='white')

def on_mouse_drag(event):
    x, y = event.x, event.y
    r = 8
    canvas.create_oval(x - r, y - r, x + r, y + r, fill='red', outline='red')
root.configure(background='green')
canvas.bind("<B1-Motion>", on_mouse_drag)
button_clear_canvas = Button(root, text="清空", command=lambda: canvas.delete("all"), font=("Arial", 12))
button_recognize_single_digit_on_canvas = Button(root, text="识别数字", command=recognize_from_canvas,
                                                 font=("Arial", 12))
button_upload_image = Button(root, text="上传图片", command=recognize_from_file, font=("Arial", 12))
result_label = Label(root, text="", font=("Arial", 14))
root.mainloop()

